<?php
/**
 * 日报
 */
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\Target as TargetService;
use think\facade\Env;
use app\common\service\OrderDelivery as OrderDeliveryService;

class Daily extends Admin
{

    protected $orderService;
    protected $orderSizeService;
    protected $orderDeliveryService;
    protected $todayLeftTime = 86400; // 今天剩余秒数

    public function initialize() {
    	parent::initialize();
    	$this->orderService = new OrderService();
    	$this->orderSizeService = new OrderSizeService();
    	$this->orderDeliveryService = new OrderDeliveryService();
    }

    public function index()
    {
    	$from	= $this->request->param('from/d', 0);
    	$factoryId	= $this->request->param('factory_id/d', 0);
    	$detail	= $this->request->param('detail/d', 0);
    	if (FACTORY_IDS != '*' && $factoryId != 0 && !in_array($factoryId, explode(',', FACTORY_IDS)) || !array_key_exists($from, config('mimo.order_from')) && $from !=0) {
    		return $this->error('非法访问！');
    	}

    	$this->todayLeftTime = strtotime(date('Y-m-d 23:59:59'))-time();
    	$this->view->engine->layout('system@layout_full');
    	$factoryKV = getFactoryKV();

    	if ($this->request->isAjax()) {
    		$fun	= $this->request->param('fun/s');
    		$res = $this->$fun();

    		if ($detail > 0) {
    			$factoryKV = ['0' => '未分配'] + $factoryKV;
    			$hisiCurMenu = ['title' => '订单列表'];
    			$this->assign('hisiHead', '');
    			return $this->assign(['hisiCurMenu' => $hisiCurMenu, 'list' => $res, 'factoryKV' => $factoryKV])->fetch('detail');
    		} else {
    			return $this->Json(1, '操作成功', $res);
    		}
    	}

    	if (FACTORY_IDS == '*') {
    		$factoryKV = ['0' => '全部工厂'] + $factoryKV;
    	} elseif($factoryId == 0) {
    		$factoryId = key($factoryKV);
    	}

    	$assign = [
    		'thisFactoryId' => $factoryId,
    		'factoryKV' => $factoryKV,
    		'thisFrom' => $from,
    		'fromKV' => ['0' => '全部'] + config('mimo.order_from'),
    	];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 产能分析
     *
     * @author KING
     * @date 2019年7月11日
     *
     */
    private function _getCnfx() {
    	$from	= $this->request->param('from/d', 0);
    	$factoryId = $this->request->param('factory_id/d', 0);
    	$detail = $this->request->param('detail/d', 0);
    	$factoryId = $factoryId?$factoryId:(FACTORY_IDS == '*'?0:FACTORY_IDS);

    	// 订单列表
    	if ($detail > 0) {
    		return $this->orderService->getOutputIng($factoryId, $from, true);
    	}

    	$cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from;

    	// 7日平均日产能
    	$output7Arr = cache(STAT_OUTPUT_AVG7 . $cacheSuffix);
    	if (empty($output7Arr))	$output7Arr = $this->orderService->getOutputByDays(7, $factoryId, $from);
    	cache(STAT_OUTPUT_AVG7 . $cacheSuffix, $output7Arr, $this->todayLeftTime);
    	$result['recently7']['jianshu'] = $output7Arr['avgJianshu'];
    	$result['recently7']['money'] = $output7Arr['avgMoney'];

    	// 14日平均日产能
    	$output14Arr = cache(STAT_OUTPUT_AVG14 . $cacheSuffix);
    	if (empty($output14Arr)) $output14Arr = $this->orderService->getOutputByDays(14, $factoryId, $from);
    	cache(STAT_OUTPUT_AVG14 . $cacheSuffix, $output14Arr, $this->todayLeftTime);
    	$result['recently14']['jianshu'] = $output14Arr['avgJianshu'];
    	$result['recently14']['money'] = $output14Arr['avgMoney'];

    	// 21日平均日产能
    	$output21Arr = cache(STAT_OUTPUT_AVG21 . $cacheSuffix);
    	if (empty($output21Arr)) $output21Arr = $this->orderService->getOutputByDays(21, $factoryId, $from);
    	cache(STAT_OUTPUT_AVG21 . $cacheSuffix, $output21Arr, $this->todayLeftTime);
    	$result['recently21']['jianshu'] = $output21Arr['avgJianshu'];
    	$result['recently21']['money'] = $output21Arr['avgMoney'];

    	// 在途产能(不含已打包的)
    	$outputIngArr = $this->orderService->getOutputIng($factoryId, $from);
    	$result['recentlyIng']['jianshu'] = $outputIngArr['jianshu'];
    	$result['recentlyIng']['orders'] = $outputIngArr['orders'];
    	$result['recentlyIng']['money'] = $outputIngArr['money'];

    	// 压力系数(在途（件）/21日平均，在途（元）/21日平均)
    	$result['pressureRate']['jianshu'] = $result['recently21']['jianshu'] ? round($result['recentlyIng']['jianshu'] / $result['recently21']['jianshu'], 2) : 0;
    	$result['pressureRate']['money'] = $result['recently21']['money'] ? round($result['recentlyIng']['money'] / $result['recently21']['money'], 2) : 0;

    	return $result;
    }

    /**
     * 各厂产能分析
     *
     * @author KING
     * @date 2020年4月16日
     *
     */
    private function _getGccnfx() {
    	$from	= $this->request->param('from/d', 0);
    	$data = [];
    	$factoryList = getFactoryKV(true);

    	foreach ($factoryList as $factoryId => $factoryName) {
    		$cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from;

    		$result = [];
    		// 在途产能
    		$result['recentlyIng']['jianshu'] = $this->orderService->getIngCountByRange($factoryId, '', $from);
    		$result['recentlyIng']['money'] = $this->orderService->getIngMoneyByRange($factoryId, '', $from);

    		// 最近21日均量/压力
    		$output21Arr = cache(STAT_OUTPUT_AVG21 . $cacheSuffix);
    		if (empty($output21Arr)) $output21Arr = $this->orderService->getOutputByDays(21, $factoryId, $from);
    		cache(STAT_OUTPUT_AVG21 . $cacheSuffix, $output21Arr, $this->todayLeftTime);
    		$result['recently21']['jianshu'] = $output21Arr['avgJianshu'];
    		$result['recently21']['money'] = $output21Arr['avgMoney'];
    		// 压力系数(在途（件）/21日平均，在途（元）/21日平均)
    		$result['recently21']['jianshuPressure'] = $result['recently21']['jianshu'] ? round($result['recentlyIng']['jianshu'] / $result['recently21']['jianshu']) : 0;
    		$result['recently21']['moneyPressure'] = $result['recently21']['money'] ? round($result['recentlyIng']['money'] / $result['recently21']['money']) : 0;

    		// 最近7日均量/压力
    		$output7Arr = cache(STAT_OUTPUT_AVG7 . $cacheSuffix);
    		if (empty($output7Arr)) $output7Arr = $this->orderService->getOutputByDays(7, $factoryId, $from);
    		cache(STAT_OUTPUT_AVG7 . $cacheSuffix, $output7Arr, $this->todayLeftTime);
    		$result['recently7']['jianshu'] = $output7Arr['avgJianshu'];
    		$result['recently7']['money'] = $output7Arr['avgMoney'];
    		// 压力系数(在途（件）/7日平均，在途（元）/7日平均)
    		$result['recently7']['jianshuPressure'] = $result['recently7']['jianshu'] ? round($result['recentlyIng']['jianshu'] / $result['recently7']['jianshu']) : 0;
    		$result['recently7']['moneyPressure'] = $result['recently7']['money'] ? round($result['recentlyIng']['money'] / $result['recently7']['money']) : 0;

    		// 最近4日出货、加工费、下单（昨天，前天，大前天，大大前天）
    		$dayStart = strtotime('-1 day 00:00:00');
    		$dayEnd = $dayStart + 86400;
    		$recently1Arr = cache(STAT_OUTGO_DAYAGO1 . $cacheSuffix);
    		if (empty($recently1Arr)) {
    			$recently1Arr['recently1']['jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 昨天
    			$recently1Arr['recently1']['money'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 昨天
    			$recently1Arr['recently1']['orders'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 昨天
    		}
    		cache(STAT_OUTGO_DAYAGO1 . $cacheSuffix, $recently1Arr, $this->todayLeftTime);
    		$result = array_merge($result, $recently1Arr);

    		$dayStart = strtotime('-2 day 00:00:00');
    		$dayEnd = $dayStart + 86400;
    		$recently2Arr = cache(STAT_OUTGO_DAYAGO2 . $cacheSuffix);
    		if (empty($recently2Arr)) {
    			$recently2Arr['recently2']['jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 前天
    			$recently2Arr['recently2']['money'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 前天
    			$recently2Arr['recently2']['orders'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 前天
    		}
    		cache(STAT_OUTGO_DAYAGO2 . $cacheSuffix, $recently2Arr, $this->todayLeftTime);
    		$result = array_merge($result, $recently2Arr);

    		$dayStart = strtotime('-3 day 00:00:00');
    		$dayEnd = $dayStart + 86400;
    		$recently3Arr = cache(STAT_OUTGO_DAYAGO3 . $cacheSuffix);
    		if (empty($recently3Arr)) {
    			$recently3Arr['recently3']['jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 大前天
    			$recently3Arr['recently3']['money'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 大前天
    			$recently3Arr['recently3']['orders'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 大前天
    		}
    		cache(STAT_OUTGO_DAYAGO3 . $cacheSuffix, $recently3Arr, $this->todayLeftTime);
    		$result = array_merge($result, $recently3Arr);

    		$dayStart = strtotime('-4 day 00:00:00');
    		$dayEnd = $dayStart + 86400;
    		$recently4Arr = cache(STAT_OUTGO_DAYAGO4 . $cacheSuffix);
    		if (empty($recently4Arr)) {
    			$recently4Arr['recently4']['jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 大大前天
    			$recently4Arr['recently4']['money'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 大大前天
    			$recently4Arr['recently4']['orders'] = $this->orderDeliveryService->getRealShipmentCountByRange($dayStart, $dayEnd, $factoryId, '', $from);	// 大大前天
    		}
    		cache(STAT_OUTGO_DAYAGO4 . $cacheSuffix, $recently4Arr, $this->todayLeftTime);
    		$result = array_merge($result, $recently4Arr);

    		// 最近4日下单均量
    		$dayStart = strtotime('-4 day 00:00:00');
    		$dayEnd = $dayStart + 4*86400;
    		$recently4avgArr = cache(STAT_RECENTLY4AVG_ORDER . $cacheSuffix);
    		if (empty($recently4avgArr)) {
    			$recently4avgArr['recently4avg']['orders'] = round(($result['recently1']['orders']+$result['recently2']['orders']+$result['recently3']['orders']+$result['recently4']['orders'])/4);
    			$recently4avgArr['recently4avg']['money'] = round($this->orderService->getOrderMoneyAllByRange($dayStart, $dayEnd, $factoryId, '', $from)/4);
    		}
    		cache(STAT_RECENTLY4AVG_ORDER . $cacheSuffix, $recently4avgArr, $this->todayLeftTime);
    		$result = array_merge($result, $recently4avgArr);

    		// 最近7日下单均量
    		$dayStart = strtotime('-7 day 00:00:00');
    		$dayEnd = $dayStart + 7*86400;
    		$recently7avgArr = cache(STAT_RECENTLY7AVG_ORDER . $cacheSuffix);
    		if (empty($recently7avgArr)) {
	    		$recently7avgArr['recently7avg']['orders'] = round($this->orderService->getOrderCountAllByRange($dayStart, $dayEnd, $factoryId, '', $from)/7);
	    		$recently7avgArr['recently7avg']['money'] = round($this->orderService->getOrderMoneyAllByRange($dayStart, $dayEnd, $factoryId, '', $from)/7);
    		}
    		cache(STAT_RECENTLY7AVG_ORDER . $cacheSuffix, $recently7avgArr, $this->todayLeftTime);
    		$result = array_merge($result, $recently7avgArr);

    		// 采购后在途产能/压力
    		$result['afterPurchasingIng']['jianshu'] = $this->orderService->getIngCountByRange($factoryId, "o.caigou_status = 1", $from);
    		$result['afterPurchasingIng']['money'] = $this->orderService->getIngMoneyByRange($factoryId, "o.caigou_status = 1", $from);
    		$result['afterPurchasingIng']['jianshuPressure'] = $result['recently21']['jianshu'] ? round($result['afterPurchasingIng']['jianshu'] / $result['recently21']['jianshu']) : 0;
    		$result['afterPurchasingIng']['moneyPressure'] = $result['recently21']['money'] ? round($result['afterPurchasingIng']['money'] / $result['recently21']['money']) : 0;

    		// 外发产能（上月）
    		$lastMonthStart = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
    		$lastMonthEnd = strtotime(date("Y-m-1 00:00:00"));
    		$lastMonthData = cache(STAT_OUTGO_LASTMONTH . $cacheSuffix);
    		if (empty($lastMonthData)) {
	    		$lastMonthData['lastMonth']['jianshu'] = $this->orderSizeService->getDaohuoCountByRange($lastMonthStart, $lastMonthEnd, $factoryId, '', $from);	// 上月件数
	    		$lastMonthData['lastMonth']['money'] = $this->orderSizeService->getDaohuoMoneyByRange($lastMonthStart, $lastMonthEnd, $factoryId, '', $from);	// 上月金额
	    		$lastMonthData['lastMonthOutgo']['jianshu'] = $this->orderSizeService->getDaohuoCountByRange($lastMonthStart, $lastMonthEnd, $factoryId, "o.outgo_status > 0", $from);	// 上月外发件数
	    		$lastMonthData['lastMonthOutgo']['money'] = $this->orderSizeService->getDaohuoMoneyByRange($lastMonthStart, $lastMonthEnd, $factoryId, "o.outgo_status > 0", $from);	// 上月外发金额
	    		$lastMonthData['lastMonthOutgoRate']['jianshu'] = $lastMonthData['lastMonth']['jianshu'] ? round($lastMonthData['lastMonthOutgo']['jianshu']*100/$lastMonthData['lastMonth']['jianshu'])."%" : '0%';
	    		$lastMonthData['lastMonthOutgoRate']['money'] = $lastMonthData['lastMonth']['money'] ? round($lastMonthData['lastMonthOutgo']['money']*100/$lastMonthData['lastMonth']['money'])."%" : '0%';
    		}
    		cache(STAT_OUTGO_LASTMONTH . $cacheSuffix, $lastMonthData, $this->todayLeftTime);
    		$result = array_merge($result, $lastMonthData);

    		// 外发产能（本月）
    		$thisMonthStart = strtotime(date("Y-m-1 00:00:00"));
    		$thisMonthEnd = time();
    		$result['thisMonth']['jianshu'] = $this->orderSizeService->getDaohuoCountByRange($thisMonthStart, $thisMonthEnd, $factoryId, '', $from);	// 本月件数
    		$result['thisMonth']['money'] = $this->orderSizeService->getDaohuoMoneyByRange($thisMonthStart, $thisMonthEnd, $factoryId, '', $from);	// 本月金额
    		$result['thisMonthOutgo']['jianshu'] = $this->orderSizeService->getDaohuoCountByRange($thisMonthStart, $thisMonthEnd, $factoryId, "o.outgo_status > 0", $from);	// 本月外发件数
    		$result['thisMonthOutgo']['money'] = $this->orderSizeService->getDaohuoMoneyByRange($thisMonthStart, $thisMonthEnd, $factoryId, "o.outgo_status > 0", $from);	// 本月外发金额
    		$result['thisMonthOutgoRate']['jianshu'] = $result['thisMonth']['jianshu'] ? round($result['thisMonthOutgo']['jianshu']*100/$result['thisMonth']['jianshu'])."%" : '0%';
    		$result['thisMonthOutgoRate']['money'] = $result['thisMonth']['money'] ? round($result['thisMonthOutgo']['money']*100/$result['thisMonth']['money'])."%" : '0%';

    		$data[$factoryId] = $result;
    	}
    	return $data;
    }

    /**
     * 获取不同环节近7天的完成件数
     *
     * @author KING
     * @date 2020年4月17日
     *
     */
    private function _getChart7daysJianshu() {
    	$from	= $this->request->param('from/d', 0);
    	$factoryId = $this->request->param('factory_id/d', 0);
    	$factoryId = $factoryId?$factoryId:(FACTORY_IDS == '*'?0:FACTORY_IDS);
    	$step = $this->request->param('step/s', '');

    	$days = [];
    	$stepName = ['cg' => '采购','ml'=>'面料处理','cj' => '裁剪','chej' => '车间','wb' => '尾部'];
    	for($i=7; $i>=1; $i--) {
    		$dayStart = strtotime("-{$i} day 00:00:00");
    		$dayEnd = $dayStart + 86400;

    		$days[] = date("m月d日", $dayStart);

    		if ($step == 'cg') {
    			$list[] = $this->orderSizeService->getCountByRange($dayStart, $dayEnd, $factoryId, "", "o.caigou_over_time", "os.order_count", $from);
    		} elseif($step == 'ml') {
    			$list[] = $this->orderService->getQuantityByCondition($factoryId, "o.caichuang_can_do_time between {$dayStart} and {$dayEnd}", $from);
    		} elseif($step == 'cj') {
    			$list[] = $this->orderSizeService->getShicaiCountByRange($dayStart, $dayEnd, $factoryId, '', $from);
    		} elseif($step == 'chej') {
    			$list[] = $this->orderSizeService->getJiaohuoCountByRange($dayStart, $dayEnd, $factoryId, '', $from);
    		} elseif($step == 'wb') {
    			$list[] = $this->orderSizeService->getDaohuoCountByRange($dayStart, $dayEnd, $factoryId, '', $from);
    		}
    	}

    	$avg = round(array_sum($list)/7);

    	$stat[] = [
    		'name' => '完成件数',
    		'data' => $list,
    	];

    	$result = ['days' => $days, 'stat' => $stat, 'stepName' => $stepName[$step], 'avg' => $avg];
    	return $result;
    }

    /**
     * 订单进度
     *
     * @author KING
     * @date 2017年4月5日
     *
     */
    private function _getDdjd() {
    	$from	= $this->request->param('from/d', 0);
    	$factoryId = $this->request->param('factory_id/d', 0);
    	$detail = $this->request->param('detail/d', 0);
    	$factoryId = $factoryId?$factoryId:(FACTORY_IDS == '*'?0:FACTORY_IDS);
    	$cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from;

    	// 订单列表
    	if ($detail > 0) {
    		$orderIds = [];
    		if ($detail == 1) $orderIds = cache(STAT_CG.$cacheSuffix);
    		elseif ($detail == 2) $orderIds = cache(STAT_ML.$cacheSuffix);
    		elseif ($detail == 3) $orderIds = cache(STAT_CJ.$cacheSuffix);
    		elseif ($detail == 4) $orderIds = cache(STAT_CHEJ.$cacheSuffix);
    		elseif ($detail == 5) $orderIds = cache(STAT_WB.$cacheSuffix);
    		elseif ($detail == 6) $orderIds = cache(STAT_DCH.$cacheSuffix);
    		$fieldStatus = "(case when o.status=99 then '已废弃' when o.status=2 then '已完成' when o.tail_status=1 then '已打包' when o.chejian_status=1 then '已车缝' when o.caichuang_status=1 then '已裁剪' when o.caigou_status=1 then '已采购' else '采购中' end) as status_txt";
    		$field = 'o.id,o.client_ordernum,o.factory_id,o.quantity,o.create_time,'.$fieldStatus;
    		return db('order o')->where('id', 'in', $orderIds)->field($field)->order('create_time desc')->select();
    	}

    	// 统计数据
    	$stat = $this->orderService->getOrderStat($factoryId, $from);

    	// 昨日数据
    	$dayStart = strtotime('-1 day 00:00:00');
    	$dayEnd = $dayStart + 86400;

    	// 【采购中】
    	$yestodayCgArr = cache(STAT_DDJD_YESTODAY_CG . $cacheSuffix);
    	if (empty($yestodayCgArr)) {
    		$yestodayCgArr['yestoday']['cg']['jianshu'] = $this->orderService->getIngCountByRange($factoryId, "o.caigou_status = 1 and o.caigou_over_time > {$dayStart} and o.caigou_over_time < {$dayEnd}", $from);
    		$yestodayCgArr['yestoday']['cg']['order'] = $this->orderService->getIngOrderByRange($factoryId, "o.caigou_status = 1 and o.caigou_over_time > {$dayStart} and o.caigou_over_time < {$dayEnd}", $from);
    	}
    	cache(STAT_DDJD_YESTODAY_CG . $cacheSuffix, $yestodayCgArr, $this->todayLeftTime);
    	$stat = array_merge_recursive($stat, $yestodayCgArr);

    	// 【面料处理】最大客户用料的面料已到料且未开始裁剪
    	$yestodayMlArr = cache(STAT_DDJD_YESTODAY_ML . $cacheSuffix);
    	if (empty($yestodayMlArr)) {
	    	$where = [
	    		['status', 'in', [0, 1]],
	    		['caichuang_status', '=', 0],
	    		['caichuang_can_do', '=', 0],
	    	];
	    	if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
	    	$mlList = db('order')->where($where)->where('id', 'IN', function ($query) use($dayStart, $dayEnd) {
	    		$query->table(Env::get('database.prefix', 'wx_').'order_material')->where("caichuang_standard = 1 and arrive_time between {$dayStart} and {$dayEnd}")->field('order_id');
	    	})->field('id,quantity')->select();
	    	$mlCount = array_sum(array_column($mlList, 'quantity'));
	    	$mlOrder = count($mlList);
	    	$yestodayMlArr['yestoday']['ml']['jianshu'] = $mlCount;
	    	$yestodayMlArr['yestoday']['ml']['order'] = $mlOrder;
    	}
    	cache(STAT_DDJD_YESTODAY_ML . $cacheSuffix, $yestodayMlArr, $this->todayLeftTime);
    	$stat = array_merge_recursive($stat, $yestodayMlArr);

    	// 【裁剪】
    	$yestodayCjArr = cache(STAT_DDJD_YESTODAY_CJ . $cacheSuffix);
    	if (empty($yestodayCjArr)) {
    		$yestodayCjArr['yestoday']['cj']['jianshu'] = $this->orderSizeService->getShicaiCountByRange($dayStart, $dayEnd, $factoryId, '', $from, true);
	    	$yestodayCjArr['yestoday']['cj']['order'] = $this->orderService->getOrdersByCondition($factoryId, "o.caichuang_status = 1 and o.caichuang_over_time > {$dayStart} and o.caichuang_over_time < {$dayEnd} and o.stock_type not in (10,11)", $from);
    	}
    	cache(STAT_DDJD_YESTODAY_CJ . $cacheSuffix, $yestodayCjArr, $this->todayLeftTime);
    	$stat = array_merge_recursive($stat, $yestodayCjArr);

    	// 【车间】
    	$yestodayChejArr = cache(STAT_DDJD_YESTODAY_CHEJ . $cacheSuffix);
    	if (empty($yestodayChejArr)) {
    		$yestodayChejArr['yestoday']['chej']['jianshu'] = $this->orderSizeService->getJiaohuoCountByRange($dayStart, $dayEnd, $factoryId, '', $from);
    		$yestodayChejArr['yestoday']['chej']['order'] = $this->orderService->getOrdersByCondition($factoryId, "o.chejian_status = 1 and o.chejian_over_time > {$dayStart} and o.chejian_over_time < {$dayEnd}", $from);
    	}
    	cache(STAT_DDJD_YESTODAY_CHEJ . $cacheSuffix, $yestodayChejArr, $this->todayLeftTime);
    	$stat = array_merge_recursive($stat, $yestodayChejArr);

    	// 【尾部】
    	$yestodayWbArr = cache(STAT_DDJD_YESTODAY_WB . $cacheSuffix);
    	if (empty($yestodayWbArr)) {
    		$yestodayWbArr['yestoday']['wb']['jianshu'] = $this->orderSizeService->getDaohuoCountByRange($dayStart, $dayEnd, $factoryId, '', $from);
	    	$yestodayWbArr['yestoday']['wb']['order'] = $this->orderService->getOrdersByCondition($factoryId, "o.tail_status = 1 and o.tail_over_time > {$dayStart} and o.tail_over_time < {$dayEnd}", $from);
	    }
	    cache(STAT_DDJD_YESTODAY_WB . $cacheSuffix, $yestodayWbArr, $this->todayLeftTime);
	    $stat = array_merge_recursive($stat, $yestodayWbArr);

    	$stat['update_time'] = date("Y年m月d日 H时i分");
    	return $stat;
    }

    /**
     * 12天出货趋势分析图表
     *
     * @author KING
     * @date 2019年7月11日
     *
     */
    private function _getChqsfx() {
    	$from	= $this->request->param('from/d', 0);
    	$factoryId = $this->request->param('factory_id/d', 0);
    	$factoryId = $factoryId?$factoryId:(FACTORY_IDS == '*'?0:FACTORY_IDS);
    	$factoryKV = ['0' => '全部工厂'] + getFactoryKV(true);

    	$day = 12;
    	$stat = $data = [];
    	$days = [];
    	for($i = 0; $i < $day; $i++) {
    		$dayStart = strtotime("+{$i} day 00:00:00");
    		$dayEnd = $dayStart+86399;
    		$days[$i] = date("m月d日", $dayStart);

    		$andWhere = [
    			['status', 'in', [0, 1]],
    			['shipment_time', 'between', [$dayStart, $dayEnd]],
    		];
    		$data1[$i] = $this->orderService->getQuantityByCondition($factoryId, $andWhere, $from);
    	}
    	// 件数
    	$stat[] = [
    		'name' => arrayGet($factoryKV, $factoryId),
    		'data' => $data1,
    	];

    	return ['days' => $days, 'stat' => $stat];
    }

    /**
     * 12天出货趋势分析图表-订单列表
     *
     * @author KING
     * @date 2019年7月12日
     *
     */
    private function _getChqsfxDetail() {
    	$from	= $this->request->param('from/d', 0);
    	$factoryId = $this->request->param('factory_id/d', 0);
    	$factoryId = $factoryId?$factoryId:(FACTORY_IDS == '*'?0:FACTORY_IDS);
    	$day = $this->request->param('day/s', '');
    	$day = str_replace('月', '-', $day);
    	$day = str_replace('日', '', $day);

    	$dayArr = explode('-', $day);
    	if ($dayArr[0] == '01' && date('m') == 12) {
    		$day = (date('Y') + 1) . '-' . $day;
    	} else {
    		$day = date('Y') . '-' . $day;
    	}

    	$dayStart = strtotime($day . ' 00:00:00');
    	$dayEnd = $dayStart+86399;

    	// 采购
    	$where = [
    		['o.status', 'in', [0, 1]],
    		['o.caigou_status', '=', 0],
    		['o.shipment_time', 'between', [$dayStart, $dayEnd]],
    	];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	$list = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->field('o.*,s.ori_pic as pic')->order('o.shipment_time asc')->select();
    	$resultCaiGou = [];
    	foreach ($list as $key => $item) {
    		$resultCaiGou[$key]['order_id'] = $item['id'];
    		$resultCaiGou[$key]['tag'] = getOrderTag($item);
    		$resultCaiGou[$key]['pic'] = $item['pic'];
    		$resultCaiGou[$key]['client_ordernum'] = $item['client_ordernum'];
    		$resultCaiGou[$key]['sku'] = $item['sku'];
    		$resultCaiGou[$key]['num'] = $item['quantity'];
    	}

    	// 裁床
    	$where = [
    		['o.status', 'in', [0, 1]],
    		['o.caigou_status', '=', 1],
    		['o.caichuang_status', '=', 0],
    		['o.shipment_time', 'between', [$dayStart, $dayEnd]],
    	];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	$list = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->field('o.*,s.ori_pic as pic')->order('o.shipment_time asc')->select();
    	$resultCaiChuang = [];
    	foreach ($list as $key => $item) {
    		$resultCaiChuang[$key]['order_id'] = $item['id'];
    		$resultCaiChuang[$key]['tag'] = getOrderTag($item);
    		$resultCaiChuang[$key]['pic'] = $item['pic'];
    		$resultCaiChuang[$key]['client_ordernum'] = $item['client_ordernum'];
    		$resultCaiChuang[$key]['sku'] = $item['sku'];
    		$resultCaiChuang[$key]['num'] = $item['quantity'];
    	}

    	// 车间
    	$where = [
    		['o.status', 'in', [0, 1]],
    		['o.caichuang_status', '=', 1],
    		['o.chejian_status', '=', 0],
    		['o.shipment_time', 'between', [$dayStart, $dayEnd]],
    	];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];

    	$list = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->field('o.*,s.ori_pic as pic')->order('o.shipment_time asc')->select();
    	$resultCheJian = [];

    	foreach ($list as $key => $item) {
    		$resultCheJian[$key]['order_id'] = $item['id'];
    		$resultCheJian[$key]['tag'] = getOrderTag($item);
    		$resultCheJian[$key]['pic'] = $item['pic'];
    		$resultCheJian[$key]['client_ordernum'] = $item['client_ordernum'];
    		$resultCheJian[$key]['sku'] = $item['sku'];
    		$resultCheJian[$key]['num'] = $item['quantity'];
    	}

    	// 尾部
    	$where = [
    		['o.status', 'in', [0, 1]],
    		['o.chejian_status', '=', 1],
    		['o.tail_status', '=', 0],
    		['o.shipment_time', 'between', [$dayStart, $dayEnd]],
    	];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	$list = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->field('o.*,s.ori_pic as pic')->order('o.shipment_time asc')->select();
    	$resultTail = [];
    	foreach ($list as $key => $item) {
    		$resultTail[$key]['order_id'] = $item['id'];
    		$resultTail[$key]['tag'] = getOrderTag($item);
    		$resultTail[$key]['pic'] = $item['pic'];
    		$resultTail[$key]['client_ordernum'] = $item['client_ordernum'];
    		$resultTail[$key]['sku'] = $item['sku'];
    		$resultTail[$key]['num'] = $item['quantity'];
    	}
		return ['caigou'=>$resultCaiGou,'caichuang'=>$resultCaiChuang,'chejian'=>$resultCheJian,'tail'=>$resultTail];
    }

    /**
     * 上月本月昨日今日出货统计图表
     *
     * @author KING
     * @date 2017年4月5日
     *
     */
    private function _getChartMonthChtj() {
    	$from	= $this->request->param('from/d', 0);
    	$factoryKV = ['0' => '全部工厂'] + getFactoryKV(true);
    	$factoryId = $this->request->param('factory_id/d', 0);
    	$detail = $this->request->param('detail/d', 0);

    	$factoryName = arrayGet($factoryKV, $factoryId, '');
    	$factoryId = $factoryId?$factoryId:(FACTORY_IDS == '*'?0:FACTORY_IDS);
    	$cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from;

    	// 订单列表
    	if ($detail > 0) {
    		$fieldStatus = "(case when o.status=99 then '已废弃' when o.status=2 then '已完成' when o.tail_status=1 then '已打包' when o.chejian_status=1 then '已车缝' when o.caichuang_status=1 then '已裁剪' when o.caigou_status=1 then '已采购' else '采购中' end) as status_txt";
    		$groupBy = "o.id,o.factory_id,o.client_ordernum,o.create_time,o.status,o.tail_status,o.chejian_status,o.caichuang_status,o.caigou_status";
    		if ($detail == 1) { // 上月出货订单
    			$orderDeliveryIds = cache(STAT_CHTJ_LASTMONTH . $cacheSuffix);
    			$field = 'o.id,o.client_ordernum,o.factory_id,sum(od.real_shipment_count) as quantity,o.create_time,'.$fieldStatus;
    			return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('o.create_time desc')->select();
    		} elseif ($detail == 2) { // 上月入仓订单
    			$orderDeliveryIds = cache(STAT_RCTJ_LASTMONTH . $cacheSuffix);
    			$field = 'o.id,o.client_ordernum,o.factory_id,sum(od.store_count) as quantity,o.create_time,'.$fieldStatus;
    			return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('o.create_time desc')->select();
    		} elseif ($detail == 3) { // 本月出货订单
    			$orderDeliveryIds = cache(STAT_CHTJ_THISMONTH . $cacheSuffix);
    			$field = 'o.id,o.client_ordernum,o.factory_id,sum(od.real_shipment_count) as quantity,o.create_time,'.$fieldStatus;
    			return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('create_time desc')->select();
    		} elseif ($detail == 4) { // 本月入仓订单
    			$orderDeliveryIds = cache(STAT_RCTJ_THISMONTH . $cacheSuffix);
    			$field = 'o.id,o.client_ordernum,o.factory_id,sum(od.store_count) as quantity,o.create_time,'.$fieldStatus;
    			return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('create_time desc')->select();
    		} elseif ($detail == 5) { // 昨日出货订单
    			$orderDeliveryIds = cache(STAT_CHTJ_YESTODAY_SHIPMENT . $cacheSuffix);
    			$field = 'o.id,o.client_ordernum,o.factory_id,sum(od.real_shipment_count) as quantity,o.create_time,'.$fieldStatus;
    			return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('create_time desc')->select();
    		} elseif ($detail == 6) { // 昨日入仓订单
    			$orderDeliveryIds = cache(STAT_CHTJ_YESTODAY_STORE . $cacheSuffix);
    			$field = 'o.id,o.client_ordernum,o.factory_id,sum(od.store_count) as quantity,o.create_time,'.$fieldStatus;
    			return db('order_delivery od')->join('order o', 'od.order_id=o.id')->where('od.id', 'in', $orderDeliveryIds)->field($field)->group($groupBy)->order('create_time desc')->select();
    		}
    	}

    	$data = [];
    	$stat = [];

    	// 上月累计出货（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
    	$lastMonthStart = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
    	$lastMonthEnd = strtotime(date("Y-m-1 00:00:00"));
    	$where = [
    		['o.status', '<>', 99],
    		['od.delivery_status', 'not in', [6, 7]],
    		['od.delivery_time', 'between', [$lastMonthStart, $lastMonthEnd]],
    	];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	$moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
    	$moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
    	$jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.real_shipment_count');
    	$orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
    	$orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
    	cache(STAT_CHTJ_LASTMONTH . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
    	$stat['last_month']['fob'][] = [
    		"name" => "出货",
    		"data" => [floatval($moneyFob)],
    	];
    	$stat['last_month']['cost'][] = [
    		"name" => "出货",
    		"data" => [floatval($moneyCost)],
    	];
    	$stat['last_month']['jianshu'][] = [
    		"name" => "出货",
    		"data" => [$jianshuTotal],
    	];
    	$stat['last_month']['orders'][] = [
    		"name" => "出货",
    		"data" => [$orderCount],
    	];

    	// 上月累计入仓（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
    	$lastMonthStart = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
    	$lastMonthEnd = strtotime(date("Y-m-1 00:00:00"));
    	$where = [
    		['o.status', '<>', 99],
    		['od.delivery_status', '=', 8],
    		['od.store_time', 'between', [$lastMonthStart, $lastMonthEnd]],
    	];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	$moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
    	$moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
    	$jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.store_count');
    	$orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
    	$orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
    	cache(STAT_RCTJ_LASTMONTH . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
    	$stat['last_month']['fob'][] = [
    		"name" => "入仓",
    		"data" => [floatval($moneyFob)],
    	];
    	$stat['last_month']['cost'][] = [
    		"name" => "入仓",
    		"data" => [floatval($moneyCost)],
    	];
    	$stat['last_month']['jianshu'][] = [
    		"name" => "入仓",
    		"data" => [$jianshuTotal],
    	];
    	$stat['last_month']['orders'][] = [
    		"name" => "入仓",
    		"data" => [$orderCount],
    	];

    	// 本月累计出货（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
    	$monthStart = strtotime(date("Y-m-1 00:00:00"));
    	$where = [
    		['o.status', '<>', 99],
    		['od.delivery_status', 'not in', [6, 7]],
    		['od.delivery_time', '>=', $monthStart],
    	];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	$moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
    	$moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
    	$jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.real_shipment_count');
    	$orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
    	$orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
    	cache(STAT_CHTJ_THISMONTH . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
    	$stat['this_month']['fob'][] = [
    		"name" => "出货",
    		"data" => [floatval($moneyFob)],
    	];
    	$stat['this_month']['cost'][] = [
    		"name" => "出货",
    		"data" => [floatval($moneyCost)],
    	];
    	$stat['this_month']['jianshu'][] = [
    		"name" => "出货",
    		"data" => [$jianshuTotal],
    	];
    	$stat['this_month']['orders'][] = [
    		"name" => "出货",
    		"data" => [$orderCount],
    	];

    	// 本月累计入仓（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
    	$monthStart = strtotime(date("Y-m-1 00:00:00"));
    	$where = [
    		['o.status', '<>', 99],
    		['od.delivery_status', '=', 8],
    		['od.store_time', '>=', $monthStart],
    	];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	$moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
    	$moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
    	$jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.store_count');
    	$orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
    	$orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
    	cache(STAT_RCTJ_THISMONTH . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
    	$stat['this_month']['fob'][] = [
    		"name" => "入仓",
    		"data" => [floatval($moneyFob)],
    	];
    	$stat['this_month']['cost'][] = [
    		"name" => "入仓",
    		"data" => [floatval($moneyCost)],
    	];
    	$stat['this_month']['jianshu'][] = [
    		"name" => "入仓",
    		"data" => [$jianshuTotal],
    	];
    	$stat['this_month']['orders'][] = [
    		"name" => "入仓",
    		"data" => [$orderCount],
    	];

    	// 昨日出货（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
    	$yestodayStart = strtotime("-1 day 00:00:00");
    	$todayStart = strtotime("0 day 00:00:00");
    	$where = [
    		['o.status', '<>', 99],
    		['od.delivery_status', 'not in', [6, 7]],
    		['od.delivery_time', 'between', [$yestodayStart, $todayStart]],
    	];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	$moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
    	$moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.real_shipment_count) as num')->findOrEmpty(), 'num', 0, true);
    	$jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.real_shipment_count');
    	$orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
    	$orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
    	cache(STAT_CHTJ_YESTODAY_SHIPMENT . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
    	$stat['yestoday']['fob'][] = [
    		"name" => "出货",
    		"data" => [floatval($moneyFob)],
    	];
    	$stat['yestoday']['cost'][] = [
    		"name" => "出货",
    		"data" => [floatval($moneyCost)],
    	];
    	$stat['yestoday']['jianshu'][] = [
    		"name" => "出货",
    		"data" => [$jianshuTotal],
    	];
    	$stat['yestoday']['orders'][] = [
    		"name" => "出货",
    		"data" => [$orderCount],
    	];

    	// 昨日入仓（FOB（元）, 加工费（元）, 件数（件）, 订单数（个））
    	$yestodayStart = strtotime("-1 day 00:00:00");
    	$todayStart = strtotime("0 day 00:00:00");
    	$where = [
    		['o.status', '<>', 99],
    		['od.delivery_status', '=', 8],
    		['od.store_time', 'between', [$yestodayStart, $todayStart]],
    	];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	$moneyFob = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->where('o.o_type', 'FOB')->fieldRaw('sum(s.price * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
    	$moneyCost = arrayGet(db('order_delivery od')->join('order o', 'o.id=od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw('sum(s.cost * od.store_count) as num')->findOrEmpty(), 'num', 0, true);
    	$jianshuTotal = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->sum('od.store_count');
    	$orderDeliveryIds = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->column('od.id');
    	$orderCount = db('order_delivery od')->join('order o', 'o.id=od.order_id')->where($where)->count('distinct od.order_id');
    	cache(STAT_CHTJ_YESTODAY_STORE . $cacheSuffix, $orderDeliveryIds, $this->todayLeftTime);
    	$stat['yestoday']['fob'][] = [
    		"name" => "入仓",
    		"data" => [floatval($moneyFob)],
    	];
    	$stat['yestoday']['cost'][] = [
    		"name" => "入仓",
    		"data" => [floatval($moneyCost)],
    	];
    	$stat['yestoday']['jianshu'][] = [
    		"name" => "入仓",
    		"data" => [$jianshuTotal],
    	];
    	$stat['yestoday']['orders'][] = [
    		"name" => "入仓",
    		"data" => [$orderCount],
    	];

    	// 昨日下单
    	$yestodayStart = strtotime("-1 day 00:00:00");
    	$todayStart = strtotime("0 day 00:00:00");
    	$where = [
    		['o.status', 'in', [0, 1, 2]],
    		['o.create_time', 'between', [$yestodayStart, $todayStart]],
    	];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	$jianshuYestoday = db('order_size os')->join('order o', 'o.id=os.order_id')->where($where)->sum('os.order_count');

    	// 今日下单
    	$todayStart = strtotime("0 day 00:00:00");
    	$where = [
    		['o.status', 'in', [0, 1, 2]],
    		['o.create_time', '>=', $todayStart],
    	];
    	if ($from) $where[] = ['o.is_auto_import', '=', $from];
    	if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	$jianshuToday = db('order_size os')->join('order o', 'o.id=os.order_id')->where($where)->sum('os.order_count');

    	$stat['recent_2days'] = [
    		["name" => "昨日", "data" => [$jianshuYestoday]],
    		["name" => "今日", "data" => [$jianshuToday]],
    	];

    	$targetService = new TargetService();

    	// 本月目标
    	$monthTargetCount = $targetService->getTarget($factoryId, 1);	// 件数
    	$monthTargetMoney = $targetService->getTarget($factoryId, 2); // 金额
    	$monthTargetCost = $targetService->getTarget($factoryId, 3); // 加工费

    	// 完成度
    	$monthData = $this->orderSizeService->getMonthCompleteData($factoryId, $from);
    	$completenessCount = $monthTargetCount ? round($monthData['count']*100/$monthTargetCount, 2) : 0;	// 件数
    	$completenessmoney = $monthTargetMoney ? round($monthData['money']*100/$monthTargetMoney, 2) : 0;	// 金额
    	$completenessCost = $monthTargetCost ? round($monthData['cost']*100/$monthTargetCost, 2) : 0;	// 加工费

    	$stat['this_month_target']['fob'] = [
    		"rate" => $completenessmoney,
    		"series" => [
    			["name" => "目标","data" => [round($monthData['money'])]],
    			["name" => "实际","data" => [round($monthTargetMoney)]]
    		],
    	];
    	$stat['this_month_target']['jianshu'] = [
    		"rate" => $completenessCount,
    		"series" => [
    			["name" => "目标","data" => [intval($monthData['count'])]],
    			["name" => "实际","data" => [intval($monthTargetCount)]]
    		],
    	];
    	$stat['this_month_target']['cost'] = [
    		"rate" => $completenessmoney,
    		"series" => [
    			["name" => "目标","data" => [round($monthData['cost'])]],
    			["name" => "实际","data" => [round($monthTargetCost)]]
    		],
    	];

    	// 货期
    	$monthStart = strtotime(date("Y-m-1 00:00:00"));
    	$where = [
    		['status', '=', 2],
    		['over_time', '>=', $monthStart],
    	];
    	if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    	if ($from) $where[] = ['is_auto_import', '=', $from];
    	$totalCount = db('order')->where($where)->sum('quantity'); // 总数
    	$standardCount = db('order')->where($where)->where('is_standard', 1)->sum('quantity'); // 货期达标数
    	$leadtimeTargetRate = ($totalCount) ? round($standardCount*100/$totalCount,2) : 0;	// 达标率 = 本月已交付订单 货期达标/总数
    	$leadtimeTarget = $targetService->getTarget($factoryId, 4); // 目标
    	$stat['this_month_target']['leadtime'] = [
    		"series" => [
    			["name" => "目标","data" => [$leadtimeTarget]],
    			["name" => "实际","data" => [$leadtimeTargetRate]]
    		],
    	];

    	// 年度
    	$yearTargetMoney = $this->orderSizeService->getYearMoney($factoryId, $from);	// 金额=本年1月1日起的 FOB+CMT+新CMT 的总出货金额
    	$yearTarget = $targetService->getTarget($factoryId, 5); // 目标金额
    	$yearTargetRate = !round($yearTarget,2) ? '' : round($yearTargetMoney*100/$yearTarget,2); // 完成率 = 已完成年度金额/年度目标金额

    	$stat['year_target'] = [
    		"rate" => $yearTargetRate,
    		"series" => [
    			["name" => "目标","data" => [$yearTarget]],
	    		["name" => "金额","data" => [$yearTargetMoney]]
    		],
    	];

    	$data = [
    		'stat' => $stat,
    		'factory_id' => $factoryId,
    		'factory_name' => $factoryName
    	];
    	return $data;
    }

    /**
     * 下单情况统计
     *
     * @author KING
     * @date 2017年4月5日
     *
     */
    private function _getChOrSit() {
    	$from	= $this->request->param('from/d', 0);
    	$sTime = microtime(true);
    	$factoryId = $this->request->param('factory_id/d', 0);
    	$factoryId = $factoryId?$factoryId:(FACTORY_IDS == '*'?0:FACTORY_IDS);
    	$type = $this->request->param('type/d', 1);

    	$cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from . '-' . $type;
    	$statData = cache(STAT_CHORSIT . $cacheSuffix);
    	if (!empty($statData)) return $statData;

    	$jianshuOutTotalArr = $moneyArr = $costOutArr = $jianshuInTotalArr = $costInArr = $days = [];
        $timeStart=$day='';
        if ($type == 1) {
            $timeStart= strtotime(date("Y-m-01 00:00:00"));
            $day = date('t', strtotime('-1 month 00:00:00'));
        }elseif($type == 2){
            $timeStart= time();
            $day = 10;
        }

    	for($i = $day; $i > 0; $i--) {
    		$dayStart = strtotime("-{$i} day 00:00:00",$timeStart);
    		$dayEnd = strtotime("-{$i} day 23:59:59",$timeStart);
    		$days[] = date("m月d日", $dayStart);

    		$where = [
    			['o.status', 'in', [0, 1, 2]],
    			['o.create_time', 'between', [$dayStart, $dayEnd]],
    		];
    		if ($from) $where[] = ['o.is_auto_import', '=', $from];
    		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    		$row = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->fieldRaw("ifnull(sum(o.quantity),0) as jianshu,ifnull(count(o.client_ordernum),0) as counts,ifnull(sum(s.cost),0) as cost")->find();

    		$jianshuInTotalArr[] = (float)arrayGet($row, 'jianshu',0);	// 订单件数
    		//$costInArr[] = (float)arrayGet($row, 'cost',0);		// 加工费
    		$countsInArr[] = arrayGet($row, 'counts',0);
    		$costInArrAll[]=(float)round((arrayGet($row, 'cost',0)*arrayGet($row, 'counts',0)),2);
    	}
        //获取平均数
        $count=count(array_diff($jianshuInTotalArr, [0]));
        $jianshuInTotalArr[]=$count?round(array_sum($jianshuInTotalArr)/$count):0;
        $costInArrAll[]=$count?round(array_sum($costInArrAll)/$count,2):0;
        $costInArr[]=$count?round(array_sum($costInArr)/$count,2):0;
        $countsInArr[]=$count?round(array_sum($countsInArr)/$count):0;
        $days[]='平均';
        $stat[0]['name'] = '订单件数';
        $stat[0]['data'] = $jianshuInTotalArr;
        $stat[1]['name'] = '总加工费';
        $stat[1]['data'] = $costInArrAll;
        $stat[2]['name'] = '订单数量';
		$stat[2]['data'] = $countsInArr;
		// $stat[3]['name'] = '加工费';
        // $stat[3]['data'] = $costInArr;

    	$statData = ['days' => $days, 'list' => $stat, 'update_time' => date("Y年m月d日 H时i分")];
    	cache(STAT_CHORSIT . $cacheSuffix, $statData, $this->todayLeftTime);
    	return $statData;
    }

    /**
     * 车间生产压力统计
     *
     * @author KING
     * @date 2017年4月5日
     *
     */
    private function _getCjyl() {
    	$from	= $this->request->param('from/d', 0);
    	$sTime = microtime(true);
    	$factoryKV = ['0' => '全部工厂'] + getFactoryKV(true);
    	$factoryId = $this->request->param('factory_id/d', 0);
    	$factoryName = arrayGet($factoryKV, $factoryId, '');
    	$factoryId = $factoryId?$factoryId:(FACTORY_IDS == '*'?0:FACTORY_IDS);

    	$todayStart = strtotime('0 day 00:00:00');
    	$monthStart = strtotime(date('Y-m-1 00:00:00'));
    	$lastMonthStart = strtotime(date("Y-m-1 00:00:00", strtotime('-1 month 00:00:00')));

    	$dayStart = strtotime('-21 day 00:00:00');
    	$dayEnd = strtotime('0 day 00:00:00');

    	$resList = [];
    	if (is_numeric($factoryId)) {
    		$groupKV = getGroupKV($factoryId);
    	} else {
    		$groupKV = db('group')->where('factory_id', 'in', $factoryId)->where('status', 1)->column('name', 'id');
    	}

    	$stat = [];
    	foreach ($groupKV as $groupId => $groupName) {
    		$cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from . '-' . $groupId;

    		$stat[$groupId]['name'] = $groupName;

    		// 应到
    		$stat[$groupId]['yd'] = 0;
    		$stat[$groupId]['sd'] = 0;

    		// 本月出货件数、本月出货加工费
    		$stat[$groupId]['month_jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($monthStart, time(), $factoryId, ['o.group_id' => $groupId], $from);
    		$stat[$groupId]['month_cost'] = $this->orderDeliveryService->getRealShipmentCostByRange($monthStart, time(), $factoryId, ['o.group_id' => $groupId], $from);

    		// 上月出货件数、上月出货加工费
    		$statGroupLastMonthArr = cache(STAT_OUTGO_GROUP_LASTMONTH . $cacheSuffix);
    		if (empty($statGroupLastMonthArr)) {
    			$statGroupLastMonthArr['last_month_jianshu'] = $this->orderDeliveryService->getRealShipmentCountByRange($lastMonthStart, $monthStart-1, $factoryId, ['o.group_id' => $groupId], $from);
    			$statGroupLastMonthArr['last_month_cost'] = $this->orderDeliveryService->getRealShipmentCostByRange($lastMonthStart, $monthStart-1, $factoryId, ['o.group_id' => $groupId], $from);
    		}
    		cache(STAT_OUTGO_GROUP_LASTMONTH . $cacheSuffix, $statGroupLastMonthArr, $this->todayLeftTime);
    		$stat[$groupId]['last_month_jianshu'] = arrayGet($statGroupLastMonthArr, 'last_month_jianshu', 0);
    		$stat[$groupId]['last_month_cost'] = arrayGet($statGroupLastMonthArr, 'last_month_cost', 0);

    		// 近21日 平均每日加工费
    		$statCostGroupAvg21Data = cache(STAT_COST_GROUP_AVG21 . $cacheSuffix);
    		if (empty($statCostGroupAvg21Data)) {
    			$statCostGroupAvg21Data = round($this->orderSizeService->getDaohuoMoneyByRange($dayStart, $dayEnd, $factoryId, ['o.group_id' => $groupId], $from)/21, 2);
    		}
    		cache(STAT_COST_GROUP_AVG21 . $cacheSuffix, $statCostGroupAvg21Data, $this->todayLeftTime);
    		$stat[$groupId]['avg_cost'] = $statCostGroupAvg21Data;

    		// 采购加工费
    		$andWhere = [
    			['o.status', 'in', [0, 1]],
    			['o.caigou_status', '=', 0],
    			['o.group_id', '=', $groupId],
    		];
    		$stat[$groupId]['caigou_cost'] = $this->orderService->getOrderMoneyAllByRange(0, time(), $factoryId, $andWhere, $from);

    		// 裁剪加工费
    		$andWhere = [
    			['o.status', 'in', [0, 1]],
    			['o.caigou_status', '=', 1],
    			['o.caichuang_status', '=', 0],
    			['o.group_id', '=', $groupId],
    		];
    		$stat[$groupId]['caijian_cost'] = $this->orderService->getOrderMoneyAllByRange(0, time(), $factoryId, $andWhere, $from);

    		// 车间生产压力
    		// 总件数
    		$andWhere = [
    			['o.status', 'in', [0, 1]],
    			['o.caichuang_status', '=', 1],
    			['o.chejian_status', '=', 0],
    			['o.group_id', '=', $groupId],
    		];
    		$stat[$groupId]['jianshu_total'] = $this->orderService->getOrderCountAllByRange(0, time(), $factoryId, $andWhere, $from);
    		// 总加工费
    		$stat[$groupId]['money_total'] = $this->orderService->getOrderMoneyAllByRange(0, time(), $factoryId, $andWhere, $from);
    	}

    	if ($stat) {
    		$resList[] = [
    			'factory_id' => $factoryId,
    			'factory_name' => $factoryName,
    			'stat' => $stat
    		];
    	}

    	return ['list' => $resList, 'update_time' => date("Y年m月d日 H时i分")];
    }

    /**
     * 出货统计图表
     *
     * @author KING
     * @date 2017年4月5日
     *
     */
    private function _getChart() {
    	$from	= $this->request->param('from/d', 0);
    	$sTime = microtime(true);
    	$factoryId = $this->request->param('factory_id/d', 0);
    	$factoryId = $factoryId?$factoryId:(FACTORY_IDS == '*'?0:FACTORY_IDS);
    	$type = $this->request->param('type/d', 1);

    	$cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $from . '-' . $type;

    	$statData = cache(STAT_SHIPMENT_CHART_DAYS30 . $cacheSuffix);
    	if (!empty($statData)) return $statData;

    	$jianshuOutTotalArr = $moneyArr = $costOutArr = $jianshuInTotalArr = $costInArr = $days = [];
    	for($i = 30; $i > 0; $i--) {
    		$dayStart = strtotime("-{$i} day 00:00:00");
    		$dayEnd = strtotime("-{$i} day 23:59:59");
    		$days[] = date("m月d日", $dayStart);

    		$where = [
    			['o.status', 'in', [0, 1, 2]],
    			['od.store_time', 'between', [$dayStart, $dayEnd]],
    			['od.delivery_status', 'not in', [6, 7]],
    		];
    		if ($from) $where[] = ['o.is_auto_import', '=', $from];
    		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    		$row = db('order_delivery od')->join('order o', 'o.id = od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->fieldRaw("SUM(od.store_count) AS jianshu,SUM(od.store_count * s.cost) AS cost")->find();
    		$jianshuInTotalArr[] = (float)arrayGet($row, 'jianshu', 0);	// 入货件数
    		$costInArr[] = (float)arrayGet($row, 'cost', 0);		// 入货加工费

    		// 出货件数、出货金额、出货加工费
    		$where = [
    			['o.status', 'in', [0, 1, 2]],
    			['od.delivery_time', 'between', [$dayStart, $dayEnd]],
    			['od.delivery_status', 'not in', [6, 7]],
    		];
    		if ($from) $where[] = ['o.is_auto_import', '=', $from];
    		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    		$list = db('order_delivery od')->join('order o', 'o.id = od.order_id')->join('sku s', 's.sku=o.sku')->where($where)->field('s.price,s.cost,o.o_type,od.real_shipment_count')->select();
    		$jianshuOutTotal = 0;
    		$money = 0;
    		$costOut = 0;
    		foreach ($list as $k => $v) {
    			$jianshu = $v['real_shipment_count'];
    			$jianshuOutTotal += $jianshu;

    			if ($v['o_type'] == 'FOB') $money += $jianshu * $v['price'];
    			elseif ($v['o_type'] == 'CMT') $money += $jianshu * $v['cost'];
    			elseif ($v['o_type'] == 'CMT2') $money += $jianshu * $v['cost'];

    			$costOut += $jianshu * $v['cost'];
    		}
    		$jianshuOutTotalArr[] = $jianshuOutTotal;	// 出货件数
    		$moneyArr[] = round($money);	// 出货金额
    		$costOutArr[] = round($costOut);		// 出货加工费
    	}

    	if ($type == 1) {
    		$stat[0]['name'] = '出货金额';
    		$stat[0]['data'] = $moneyArr;
    		$stat[1]['name'] = '出货加工费';
    		$stat[1]['data'] = $costOutArr;
    		$stat[2]['name'] = '入货加工费';
    		$stat[2]['data'] = $costInArr;
    	} elseif ($type == 2) {
    		$stat[0]['name'] = '出货件数';
    		$stat[0]['data'] = $jianshuOutTotalArr;
    		$stat[1]['name'] = '入货件数';
    		$stat[1]['data'] = $jianshuInTotalArr;
    	}

    	$statData = ['days' => $days, 'list' => $stat, 'update_time' => date("Y年m月d日 H时i分")];
    	cache(STAT_SHIPMENT_CHART_DAYS30 . $cacheSuffix, $statData, $this->todayLeftTime);
    	return $statData;
    }


	/**
     * 针织梭织统计
     *
     * @author KING
     * @date 2019年7月17日
     *
     */
    private function _getSkutypeStat() {
    	$from	= $this->request->param('from/d', 0);
    	$factoryId = $this->request->param('factory_id/d', 0);
    	$factoryId = $factoryId?$factoryId:(FACTORY_IDS == '*'?0:FACTORY_IDS);

    	$days = [];
    	$skuTypeArr = ['zz' => '针织', 'sz' => '梭织'];
    	for($i = 7; $i > 0; $i--) {
    		$n = 7-$i;
    		$dayStart = strtotime("-{$i} day 00:00:00");
    		$dayEnd = strtotime("-{$i} day 23:59:59");

    		// 日期列表
    		$days[] = date('n月j日', $dayStart);

    		foreach ($skuTypeArr as $stk => $stv) {
    			// 针织/梭织下单-成本费用
    			$where = [
    				['o.status', 'in', [0, 1, 2]],
    				['o.create_time', 'between', [$dayStart, $dayEnd]],
    				['s.sku_type', '=', $stv],
    			];
    			if ($from) $where[] = ['o.is_auto_import', '=', $from];
    			if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    			$orders[$stk][$n]['m'] = arrayGet(db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->fieldRaw('sum(o.quantity*s.cost) as num')->findOrEmpty(), 'num', 0, true);

    			// 针织下单-下单件数
    			$where = [
    				['o.status', 'in', [0, 1, 2]],
    				['o.create_time', 'between', [$dayStart, $dayEnd]],
    				['s.sku_type', '=', $stv],
    			];
    			if ($from) $where[] = ['o.is_auto_import', '=', $from];
    			if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    			$orders[$stk][$n]['i'] = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->sum('o.quantity');

    			// 针织/梭织下单-订单数
    			$where = [
    				['o.status', 'in', [0, 1, 2]],
    				['o.create_time', 'between', [$dayStart, $dayEnd]],
    				['s.sku_type', '=', $stv],
    			];
    			if ($from) $where[] = ['o.is_auto_import', '=', $from];
    			if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    			$orders[$stk][$n]['o'] = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->count('o.id');


    			// 针织/梭织出货-成本费用
    			$where = [
    				['o.status', 'in', [0, 1, 2]],
    				['o.shipment_time', 'between', [$dayStart, $dayEnd]],
    				['s.sku_type', '=', $stv],
    			];
    			if ($from) $where[] = ['o.is_auto_import', '=', $from];
    			if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    			$shipments[$stk][$n]['m'] = arrayGet(db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->fieldRaw('sum(o.quantity*s.cost) as num')->findOrEmpty(), 'num', 0, true);

    			// 针织/梭织出货-下单件数
    			$where = [
    				['o.status', 'in', [0, 1, 2]],
    				['o.shipment_time', 'between', [$dayStart, $dayEnd]],
    				['s.sku_type', '=', $stv],
    			];
    			if ($from) $where[] = ['o.is_auto_import', '=', $from];
    			if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    			$shipments[$stk][$n]['i'] = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->sum('o.quantity');

    			// 针织/梭织出货-订单数
    			$where = [
    				['o.status', 'in', [0, 1, 2]],
    				['o.shipment_time', 'between', [$dayStart, $dayEnd]],
    				['s.sku_type', '=', $stv],
    			];
    			if ($from) $where[] = ['o.is_auto_import', '=', $from];
    			if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    			$shipments[$stk][$n]['o'] = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->count('o.id');
    		}
    	}

    	$dayEnd = strtotime('0 day 00:00:00');
    	$dayStartArr = [
    		'7' => [strtotime('-7 day 00:00:00'), $dayEnd],
    		'14' => [strtotime('-14 day 00:00:00'), $dayEnd],
    		'21' => [strtotime('-21 day 00:00:00'), $dayEnd],
    		'1' => [0, $dayEnd+86400], // 在途
    	];

    	foreach ($dayStartArr as $k => $dayRange) {
    		$dayStart = $dayRange[0];
    		$dayEnd = $dayRange[1];
    		foreach ($skuTypeArr as $stk => $stv) {
    			// 针织/梭织下单-成本费用
    			if ($k != 1) {
    				$day[$stk][$k]['m'] = $this->orderService->getOrderMoneyAllByRange($dayStart, $dayEnd, $factoryId, ['s.sku_type' => $stv], $from);
    			} else {
    				$andWhere = [
    					['o.create_time', 'between', [$dayStart, $dayEnd]],
    					['s.sku_type', '=', $stv],
    				];
    				$day[$stk][$k]['m'] = $this->orderService->getIngMoneyByRange($factoryId, $andWhere, $from);
    			}

    			// 针织/梭织下单-下单件数
    			if ($k != 1) {
    				$day[$stk][$k]['i'] = $this->orderService->getOrderCountAllByRange($dayStart, $dayEnd, $factoryId, ['s.sku_type' => $stv], $from);
    			} else {
    				$andWhere = [
    					['o.create_time', 'between', [$dayStart, $dayEnd]],
    					['s.sku_type', '=', $stv],
    				];
    				$day[$stk][$k]['i'] = $this->orderService->getIngCountByRange($factoryId, $andWhere, $from);
    			}

    			// 针织/梭织下单-订单数
    			$andWhere = [
    				['o.create_time', 'between', [$dayStart, $dayEnd]],
    				['s.sku_type', '=', $stv],
    			];
    			if ($k != 1) {
    				$day[$stk][$k]['o'] = $this->orderService->getOrdersByCondition($factoryId, $andWhere, $from);
    			} else {
    				$day[$stk][$k]['o'] = $this->orderService->getIngOrderByRange($factoryId, $andWhere, $from);
    			}
    		}
    	}

    	// 压力系数(在途（件）/21日平均，在途（元）/21日平均)
    	$pressureRate['zz']['m'] = $day['zz'][21]['m'] ? round($day['zz'][1]['m'] / $day['zz'][21]['m'], 2) : 0;
    	$pressureRate['zz']['i'] = $day['zz'][21]['i'] ? round($day['zz'][1]['i'] / $day['zz'][21]['i'], 2) : 0;
    	$pressureRate['zz']['o'] = $day['zz'][21]['o'] ? round($day['zz'][1]['o'] / $day['zz'][21]['o'], 2) : 0;
    	$pressureRate['sz']['m'] = $day['sz'][21]['m'] ? round($day['sz'][1]['m'] / $day['sz'][21]['m'], 2) : 0;
    	$pressureRate['sz']['i'] = $day['sz'][21]['i'] ? round($day['sz'][1]['i'] / $day['sz'][21]['i'], 2) : 0;
    	$pressureRate['sz']['o'] = $day['sz'][21]['o'] ? round($day['sz'][1]['o'] / $day['sz'][21]['o'], 2) : 0;

    	$dayStartArr = [
    		'last' => [strtotime(date('Y-m-01 00:00:00', strtotime('-1 month'))), strtotime(date("Y-m-1 00:00:00"))],  // 上月
    		'this' => [strtotime(date("Y-m-1 00:00:00")), strtotime(date('Y-m-01 00:00:00', strtotime('+1 month')))], // 本月
    	];
    	$monthShipment = ['zz' => ['last' => ['m'=>0,'i'=>0,'o'=>0], 'this' => ['m'=>0,'i'=>0,'o'=>0]], 'sz' => ['last' => ['m'=>0,'i'=>0,'o'=>0], 'this' => ['m'=>0,'i'=>0,'o'=>0]]];
    	foreach ($dayStartArr as $k => $dayRange) {
    		$dayStart = $dayRange[0];
    		$dayEnd = $dayRange[1];

    		$where = [
    			['o.status', '=', 2],
    			['o.over_time', 'between', [$dayStart, $dayEnd]],
    		];
    		if ($from) $where[] = ['o.is_auto_import', '=', $from];
    		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
    		$list = db('order_size os')->join('order o', 'o.id = os.order_id')->join('sku s', 's.sku = o.sku ')->where($where)->field('os.daohuo_count,os.order_count,s.sku_type,s.cost')->select();

    		foreach ($list as $sv) {
    			$jianshu = $sv['daohuo_count'];
    			// 加工费
    			$moneyCost = $sv['order_count'] * $sv['cost'];

    			if ($sv['sku_type'] == '针织') {
    				$monthShipment['zz'][$k]['m'] += $moneyCost;
    				$monthShipment['zz'][$k]['i'] += $jianshu;
    				$monthShipment['zz'][$k]['o'] += 1;
    			} elseif ($sv['sku_type'] == '梭织') {
    				$monthShipment['sz'][$k]['m'] += $moneyCost;
    				$monthShipment['sz'][$k]['i'] += $jianshu;
    				$monthShipment['sz'][$k]['o'] += 1;
    			}
    		}
    	}

    	$result = [
    		'days' => $days,					// 日期列表
    		'zz_orders' => $orders['zz'],		// 针织下单列表
    		'zz_shipments' => $shipments['zz'],	// 针织出货列表
    		'sz_orders' => $orders['sz'],		// 梭织下单列表
    		'sz_shipments' => $shipments['sz'],	// 梭织出货列表
    		// 针织
    		'zz' => [
    			'day7' => $day['zz'][7],			// 	7天日均
    			'day14' => $day['zz'][14],		// 14天日均
    			'day21' => $day['zz'][21],		// 21天日均
    			'ing' => $day['zz'][1],			// 在途量
    			'pressure' => $pressureRate['zz'],	// 压力系数
    			'lastmonth_shipment' => $monthShipment['zz']['last'],	// 上月出货
    			'thismonth_shipment' => $monthShipment['zz']['this'],	// 本月出货
    		],
    		// 梭织
    		'sz' => [
    			'day7' => $day['sz'][7],		// 	7天日均
    			'day14' => $day['sz'][14],		// 14天日均
    			'day21' => $day['sz'][21],		// 21天日均
    			'ing' => $day['sz'][1],			// 在途量
    			'pressure' => $pressureRate['sz'],	// 压力系数
    			'lastmonth_shipment' => $monthShipment['sz']['last'],	// 上月出货
    			'thismonth_shipment' => $monthShipment['sz']['this'],	// 本月出货
    		],
    	];

    	return $result;
    }

}